<template>
  <div class="addBrand-container">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      :inline="true"
      label-width="180px"
      class="demo-ruleForm"
    >
      <el-form-item label="菜品名称:" prop="name">
        <el-input
          v-model="formData.name"
          placeholder="请填写菜品名称"
          maxlength="20"
        />
      </el-form-item>
      <el-form-item label="菜品分类:" prop="categoryId">
        <el-select v-model="formData.categoryId" placeholder="请选择菜品分类">
          <el-option
            v-for="item in categoryList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="菜品价格:" prop="price">
        <el-input v-model="formData.price" placeholder="请设置菜品价格" />
      </el-form-item>
      <el-form-item label="口味做法配置:">
        <el-form-item>
          <div class="flavorBox">
            <el-button
              v-if="formData.flavors.length == 0"
              type="primary"
              @click="handleAdd"
              >+ 添加口味</el-button
            >
            <div v-if="formData.flavors.length != 0" class="flavor">
              <div class="title">
                <span>口味名（3个字内）</span
                ><span>口味标签（输入标签回车添加）</span>
              </div>
              <div class="cont">
                <div
                  v-for="(dishFlavor, index) in formData.flavors"
                  :key="dishFlavor.id"
                  class="items"
                >
                  <div class="itTit">
                    <div class="selectInput">
                      <div>
                        <el-input
                          v-model="dishFlavor.name"
                          type="text"
                          style="width: 100%"
                          placeholder="请输入口味"
                          @focus="handleShowOption(index)"
                          @blur="handleHideOption()"
                          @input="handleHideOption()"
                        />
                      </div>
                      <div v-show="optionInex == index" class="flavorSelect">
                        <span
                          v-for="(item, ind) in flavorSelectData"
                          :key="ind"
                          class="items"
                          @click.stop="handleCheckOption(item, index)"
                          >{{ item.name }}</span
                        >
                        <span v-if="flavorSelectData == []" class="none"
                          >无数据</span
                        >
                      </div>
                    </div>
                  </div>
                  <div class="labItems">
                    <el-tag
                      v-for="(item, ind) in dishFlavor.value"
                      :key="ind"
                      closable
                      @close="handleDel(ind, index)"
                      >{{ item }}</el-tag
                    >
                    <el-input
                      v-if="inputIndex == index"
                      ref="inputRef"
                      v-model="inputValue"
                      @keyup.enter="handleAddItem(index)"
                      @blur="handleAddItem(index)"
                    />
                    <el-button v-else @click="handleShowInput(index)"
                      >+ 口味标签</el-button
                    >
                  </div>
                  <span class="delBut" @click="handleDelFlavor(index)"
                    >删除</span
                  >
                </div>
              </div>
              <el-button type="primary" @click="handleAdd"
                >+ 添加口味</el-button
              >
            </div>
          </div>
        </el-form-item>
      </el-form-item>
      <el-form-item label="菜品图片:" prop="image" class="uploadImg">
        <el-upload
          class="avatar-uploader"
          action="/common/upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :on-change="onChange"
          ref="upload"
        >
          <!-- <img v-if="formData.image" :src="require('@/assets/dish-images/'+ formData.image)" class="avatar"> -->
          <img v-if="formData.image" :src="formData.image" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item label="菜品描述:" prop="description" class="address">
        <el-input
          v-model="formData.description"
          type="textarea"
          :rows="3"
          placeholder="菜品描述，最长200字"
          maxlength="777"
        />
      </el-form-item>
      <div class="subBox">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="submitForm()">保存</el-button>
        <!-- <el-button type="primary" class="continue" @click="submitForm('ruleForm','goAnd')">保存并继续添加菜品</el-button> -->
      </div>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, nextTick } from "vue";
import { validPrice } from "@/utils/validate";
import { getDishById, addDish, editDish } from "@/api/dish/dish";
import { getListByType as getCategoryListByType } from "@/api/category/category";
import { ElMessage } from "element-plus";

const props = defineProps({
  id: {
    type: String,
    default: undefined,
  },
});
const emits = defineEmits(["close"]);
const formRef = ref();
const formData = ref({
  id: "",
  name: "",
  price: "",
  code: "",
  image: "",
  description: "",
  flavors: [],
  status: 1,
  categoryId: "",
});
const formRules = reactive({
  name: [{ required: true, message: "请填写菜品名称", trigger: "blur" }],
  categoryId: [
    { required: true, message: "请选择菜品分类", trigger: "change" },
  ],
  price: [{ required: true, validator: validPrice, trigger: "blur" }],
});
const categoryList = ref([]);
const optionInex = ref(); //口味下拉显示
const flavorSelectData = ref([]);
const inputRef = ref();
const inputIndex = ref();
const inputValue = ref("");

// const id = ref("");
// const restKey = ref(0);
// const textarea = ref("");
// const value = ref("");
const imageUrl = ref("");
// const dishFlavors = ref([]);
// const vueRest = ref("1");
// const index = ref(0);
// const inputStyle = ref({ flex: 1 });

// const mak = ref(false);

/* 获取菜品分类、获取菜品对象、获取口味列表 */
const init = () => {
  if (props.id) {
    getDishById({ id: props.id }).then((res) => {
      res.data.flavors = res.data.flavors.map((obj) => {
        obj.value = JSON.parse(obj.value);
        return obj;
      });
      formData.value = res.data;
      formData.value.price = (formData.value.price / 100).toFixed(2);
    });
  }
  getCategoryListByType({ type: 1 }).then((res) => {
    categoryList.value = res.data;
  });
  flavorSelectData.value = [
    {
      id: "",
      dishId: props.id,
      name: "甜味",
      value: ["无糖", "少糖", "半糖", "多糖", "全糖"],
    },
    {
      id: "",
      dishId: props.id,
      name: "温度",
      value: ["热饮", "常温", "去冰", "少冰", "多冰"],
    },
    {
      id: "",
      dishId: props.id,
      name: "忌口",
      value: ["不要葱", "不要蒜", "不要香菜", "不要辣"],
    },
    {
      id: "",
      dishId: props.id,
      name: "辣度",
      value: ["不辣", "微辣", "中辣", "重辣"],
    },
  ];
};
init();

/* 添加口味按钮 */
const handleAdd = () => {
  formData.value.flavors.push({
    name: "",
    value: [],
    showOption: false,
  });
};

/* 显示口味下拉列表 */
const handleShowOption = (index) => {
  optionInex.value = index;
};

/* 隐藏口味下拉列表 */
const handleHideOption = () => {
  setTimeout(() => {
    optionInex.value = undefined;
  }, 200);
};

/* 选择口味 */
const handleCheckOption = (item, index) => {
  formData.value.flavors.splice(index, 1, item);
};

/* 删除口味信息按钮 */
const handleDelFlavor = (index) => {
  formData.value.flavors.splice(index, 1);
};

/* 添加口味标签按钮 */
const handleShowInput = (index) => {
  inputIndex.value = index;
  nextTick(() => {
    inputRef.value[0].focus();
  });
};
const handleAddItem = (index) => {
  if (inputValue.value) {
    formData.value.flavors[index].value.push(inputValue.value);
  }
  inputValue.value = "";
  inputIndex.value = undefined;
};

/* 删除口味标签按钮 */
const handleDel = (ind, index) => {
  formData.value.flavors[index].value.splice(ind, 1);
};

const submitForm = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      /* let params = { ...this.ruleForm };
            params.flavors = this.dishFlavors
            params.status = this.ruleForm ? 1 : 0;
            params.price *= 100;
            params.categoryId = this.ruleForm.categoryId;
            params.flavors = this.dishFlavors.map((obj) => ({
                ...obj,
                value: JSON.stringify(obj.value),
            }));
            delete params.dishFlavors;
            if (!this.imageUrl) {
                this.$message.error("请上传菜品图片");
                return;
            } */
      formData.value.price = formData.value.price * 100;
      let params = JSON.parse(JSON.stringify(formData.value));
      params.flavors.map((item) => {
        const value = JSON.stringify(item.value);
        item.value = value;
      });
      if (!formData.value.id) {
        addDish(params).then((res) => {
          if (res.code == 0) {
            ElMessage({ type: "error", message: res.msg });
          } else {
            ElMessage({ type: "success", message: res.data });
          }
        });
        close();
		    init();
      } else {
        editDish(params).then((res) => {
          ElMessage({ type: "success", message: "菜品修改成功！" });
          close();
        });
      }
    }
  });
};

const handleAvatarSuccess = (response, file, fileList) => {
  // 拼接down接口预览
  if (response.code === 0 && response.msg === "未登录") {
    window.top.location.href = "/backend/page/login/login.html";
  } else {
    formData.value.image = response.data;
  }
};

const onChange = (file) => {
  if (file) {
    const suffix = file.name.split(".")[1];
    const size = file.size / 1024 / 1024 < 2;
    if (["png", "jpeg", "jpg"].indexOf(suffix) < 0) {
      this.$message.error("上传图片只支持 png、jpeg、jpg 格式！");
      this.$refs.upload.clearFiles();
      return false;
    }
    if (!size) {
      this.$message.error("上传文件大小不能超过 2MB!");
      return false;
    }
    return file;
  }
};

const close = () => {
  emits("close");
};
</script>

<style lang="scss" scoped>
.cont .delBut {
  padding: 0 10px;
  cursor: pointer;
  line-height: 40px;
}

.labItems .el-button {
  color: #f19c59;
  margin: 5px;
  line-height: 26px;
  height: 26px;
  padding: 0 10px;
  background: #fdf4eb;
  border-radius: 3px;
  border: solid 1px #fae2cd;
  font-size: 12px;
  font-weight: normal;
}

.labItems .el-button:hover {
  color: #fff;
  background-color: #ffc200;
}

.labItems .el-input {
  width: 90px;
  height: 26px;
  margin: 5px;
}

.selectInput {
  position: relative;
  width: 100%;
  min-width: 100px;
}
.selectInput .flavorSelect {
  position: absolute;
  width: 100%;
  padding: 0 10px;
  border-radius: 3px;
  border: solid 1px #ff903d;
  line-height: 30px;
  text-align: center;
  background: #fff;
  top: 50px;
  z-index: 99;
}
.selectInput .flavorSelect .items {
  cursor: pointer;
  width: 100%;
  line-height: 35px;
  border-bottom: solid 1px #f4f4f4;
  color: #666;
}
.selectInput .flavorSelect .none {
  font-size: 14px;
}

.uploadImg .el-form-item__label::before {
  content: "*";
  color: #f56c6c;
  margin-right: 4px;
}
</style>
